package com.itheima.controller;



import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.itheima.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {


    @PostMapping("/upload")
    private R upload(MultipartFile file) throws IOException {  //SpringMVC提供简化上传操作的工具类

        //获取文件名
        String filename = file.getOriginalFilename();

        //获取文件的后缀名
        String substring = filename.substring(filename.lastIndexOf("."));
        //System.out.println(substring);

        //生成一个文件名
        String newFile = UUID.randomUUID() + substring;

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tA4s6rKGJ6NrvhwigyL";
        String accessKeySecret = "XuVoucaEZyo9GMqs8OHVDyPuffvwTu";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "reggie-dish-imgs";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = newFile;
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        //String filePath= "D:\\img\\"+filename;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功，则返回200。
            System.out.println(result.getResponse().getStatusCode());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //判断文件夹是否存在，不存在则创建
//        File Path = new File("D:\\img\\");
//        if (!Path.exists()){
//            Path.mkdirs();
//        }
//
//        //将文件存储到指定的位置
//        file.transferTo(new File(filePath,newFile)); //上传

        return R.success(newFile);
    }

    //图片文件下载
    @GetMapping("/download")
    private void download(String name, HttpServletResponse response) throws IOException {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tA4s6rKGJ6NrvhwigyL";
        String accessKeySecret = "XuVoucaEZyo9GMqs8OHVDyPuffvwTu";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "reggie-dish-imgs";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = name;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(bucketName, objectName);
        IOUtils.copy(ossObject.getObjectContent(), response.getOutputStream());

        //使用字节输入流
//        FileInputStream fis = new FileInputStream(objectName);
//
//        //获取输出流
//        ServletOutputStream os = response.getOutputStream();
//
//        //将获取的流写到指定地址
//        byte[] bytes = new byte[1024];
//        int len;
//        while ((len = fis.read(bytes))!=-1){
//            os.write(bytes,0,len);
//        }
//        fis.close();




    }


}
